package com.jweb.framework.security.crypto.cipher.asymmetric;

import java.security.Key;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.jweb.framework.security.crypto.common.EAlgorithm;
import com.jweb.framework.security.crypto.common.ECipherMode;

/**
 * 修改人： Thomas
 * 修改内容：新增 
 * 类说明：
 */
public class DefaultBase64EncodedAsymCipherer implements Base64EncodedAsymCipherer {
	
	protected EAlgorithm algorithm = EAlgorithm.RSA;
	protected String charsetName = "UTF-8";
	protected ECipherMode mode ;
	protected Key key ;
	
	public void setAlgorithm(EAlgorithm algorithm) {
		this.algorithm = algorithm;
	}

	public void setCharsetName(String charsetName) {
		this.charsetName = charsetName;
	}

	public void setMode(ECipherMode mode) {
		this.mode = mode;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	@Override
	public String encrypt(String source) {
		try {
			Cipher cipher = Cipher.getInstance(this.algorithm.toString());
			int num = mode.ordinal() ;
			switch (num) {
				case 0: // 加密
					BASE64Encoder encoder = new BASE64Encoder();
					byte[] byte0 = source.getBytes(this.charsetName);
					cipher.init(Cipher.ENCRYPT_MODE, this.key);
					return encoder.encode(cipher.doFinal(byte0));
				case 1: // 解密
					BASE64Decoder decoder = new BASE64Decoder();
					byte[] byte1 = decoder.decodeBuffer(source);
					cipher.init(Cipher.DECRYPT_MODE, this.key);
					return new String(cipher.doFinal(byte1), this.charsetName);
			}
			
			return null ;
		} catch (Exception e) {
			throw new AsymmetricEncryptionException("Error encrypting/decrypting message; mode=" + this.mode, e);
		}
	}

}
